<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div id="top">
          <img src="../../assets/img/logo.png" alt="" height="30" style="float: left">
          <div class="notification-wrapper">
            <div style="text-align: right;padding-top: 0rem;display: inline-block;position: fixed;right: 14rem;cursor: pointer" @click="openMsg()">
              <img src="../../assets/img/msg.png" alt="" height="40"/>
              <div v-if="unread" class="notification-dot">{{unReadNumber}}</div>
            </div>
          </div>
          <div style="text-align: right;padding-top: 0rem;display: inline-block;position: fixed;right: 10rem;cursor: pointer" @click="userInfo"><img src="../../assets/img/setting.png" alt="" height="40"/></div>
          <div style="text-align: right;padding-top: 0.45rem;color: #6E7072;display: inline-block;position: fixed;right: 4rem;cursor: default">{{userName}}</div>
          <el-dropdown>
            <div class="avatar-container" style="cursor: pointer"><span class="avatar-content">{{info}}</span></div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="logOut">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-scrollbar>
          <el-menu :default-active="currentNav" :unique-opened = true @open="handleOpen">
              <div style="color: #6E7072;font-weight: bolder;text-align: left;font-size: 0.79rem;padding: 1rem 1.15rem;cursor: pointer" @click="gostaging()">工作台</div>
            <el-sub-menu :index="index.toString()" v-for="(item,index) in menuList" >
              <template #title>
                <span style="color: #6E7072;font-weight: bolder">{{item.menuName}}</span>
              </template>
              <el-menu-item-group  v-for="(item2,index2) in item.children">
                <div v-if="item2.children.length>0">
                  <el-sub-menu>
                    <template #title>
                      <span style="color: #6E7072;font-weight: bolder">{{item2.menuName}}</span>
                    </template>
                    <el-menu-item-group  v-for="(item3,index3) in item2.children">
                      <el-menu-item v-if="item3.children.length ==0" :index="index+'-'+index3" @click="pushToPage(item3)">{{item3.menuName}}</el-menu-item>
                    </el-menu-item-group>
                  </el-sub-menu>
                </div>
                <el-menu-item v-if="item2.children.length ==0" :index="index+'-'+index2" @click="pushToPage(item2)">{{item2.menuName}}</el-menu-item>
              </el-menu-item-group>
            </el-sub-menu>
          </el-menu>
          </el-scrollbar>
        </el-aside>

        <el-main>
          <div>
            <router-view/>
          </div>
          <div>
            <el-drawer v-model="messageFlag" title="消息中心" :direction="direction" :before-close="handleClose">
             <div v-for="item in messageTableList">
               <el-card class="box-card">
                 <template #header>
                   <div class="card-header">
                     <span style="text-align: left;font-size: 0.8rem">{{item.messageTitle}}</span>
                   </div>
                 </template>
                 <div class="sx" style="font-size: 0.8rem;text-align: left">
                 </div>
                 <div  style="font-size: 0.8rem;text-align: left;color: #6E7072;margin-top: 0.2rem">
                  发送时间: {{new Date(item.sendTime).toLocaleString()}}
                 </div>
               </el-card>
             </div>
            </el-drawer>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import {getLoginInfo, getMenuListByUser} from "../../api/home";
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {ElMessage, ElNotification} from 'element-plus';
import {useUsersStore, webscoketObject} from "../../store/userInfo.ts";

let userName =ref('');
let info =ref('');
let menuList = ref([]);
let currentNav = ref('');
const router = useRouter();
let menuFlag = ref(true);
let messageFlag = ref(false);
let socketMessage = ref('');
let messageTableList = ref<any>('');
let sendMessage= ref({
  pageNum: 1,
  pageSize: 999999999,
  messageCode: "1"
})
let total = ref<number>(0)
let store = useUsersStore();
let wsx = webscoketObject();
let unread = ref(false)
let{ws} =wsx
let {name,role,token} = store;
const websocketUrl = import.meta.env.VITE_WS;
let unReadNumber = ref<number>(0)
let socket
onMounted(async () => {
  connectWebSocket(websocketUrl);
  let res = await getMenuListByUser();
  let loginInfo =await getLoginInfo();
  if (res.code == 8333){
    ElMessage.error(res.msg)
    store.$reset();
    await router.push("/")
  }
  menuList.value =res.data;
  userName.value=loginInfo.data.userName;
  if (userName.value!==''){
    info.value= userName.value.slice(-1);
  }
})

function connectWebSocket(url: string) {
  wsx.ws = new WebSocket(url,[store.token]);
  wsx.ws.addEventListener('open',async () => {
    await getUnRead()
    console.log('打开socket连接');
  });
  wsx. ws.addEventListener('message',async (event) => {
    console.log('Home收到消息', event.data);
      let parse = JSON.parse(event.data);
      switch (parse.resultCode){
        case '202':
          const parsedMessageData = parseInt(parse.messageData);
          unReadNumber.value = Math.min(99, parsedMessageData);
          unread.value = unReadNumber.value > 0;
          break;
        case '200':
          await messageAlert(parse)
            setTimeout( await getUnRead(),200)
          break;
        default:
          await getUnRead()
          try {
            socketMessage.value = JSON.parse(parse.messageData)
            total.value = socketMessage.value.total
          }catch (e) {
            socketMessage.value =''
          }
      }
  });

  wsx.ws.addEventListener('close', async () => {
      console.log('关闭连接');
      console.log('正在重连');
      await  getLoginInfo();
      connectWebSocket(url);
  });

  wsx.ws.addEventListener('error', (error) => {
    console.error('报错了:', error);
  });
}

const pushToPage =  (item2) => {
  menuFlag.value = true;
  messageFlag.value = false;
  router.push(item2.url)
}
const logOut = async() => {
  store.$reset();
  await router.push("/")
}
const userInfo =async() =>{
  await router.push("/system/account")
}
const gostaging = async () => {
  await router.push("/staging")
}
const openMsg = async () => {
 await wsx.ws.send(  JSON.stringify(sendMessage.value))
    setTimeout(async() => {
      messageTableList.value = socketMessage.value.list;
      console.log(socketMessage.value.list)
      messageFlag.value = true;
      await getUnRead()
      messageTableList.value.forEach((item,index) => {
        const elements = item.messageContent.split(" ");
        let innerHTML = "";
        switch (item.messageType) {
          case "1":
            innerHTML = "<div><b>" + elements[0] + "</b> <b style='color:#ea621f'>" + elements[1] + "</b></div>" +
                "<div><b>" + elements[2] + "</b> <b style='color:#ea621f'>" + elements[3] + "</b></div>";
            break;
          case "2":
            innerHTML = "<div><b style='color:#ea621f'>" + elements[0] + "</b> <b>" + elements[1] +
                "</b> " + "<b style='color:#ea621f'>" + elements[2] + "</b></div>" +
                "<div><b>" + elements[3] + "</b> " + "<b style='color:#ea621f'>" + elements[4] + "</b></div>" +
                "<div><b>" + elements[5] + "</b> <b style='color:#ea621f'>" + elements[6] + "</b></div>";
            break;
          default:
            innerHTML =item.messageContent
            break;
        }
        document.getElementsByClassName('sx')[index].innerHTML = innerHTML;
      })
    },200)

}
const getUnRead = async () => {
  await wsx.ws.send(  JSON.stringify({messageCode:2}))

}
const  messageAlert = async (pase) => {
  ElNotification({
    title: '收到消息',
    dangerouslyUseHTMLString: true,
    message:  pase.messageContent,
  })
}
</script>

<style scoped>
.common-layout{
  height: 99.9vh;
  overflow-y: hidden;
}
.common-layout>>>.el-container{
  height: 99.9vh;
  overflow-y: hidden;
}
#top{
  width: 100%;
  height: 100%;
  padding-top: 0.58%;
  overflow: hidden;
}
#top>>>.el-dropdown{
  float: right;
}
.el-header{
  background-color: #FFFFFF;
}
.avatar-container {
  height: 2.5rem;
  width: 2.5rem;
  display: inline-block;
  background: #409EFF;
  text-align: center;
  border-radius: 1.5rem;
  vertical-align: -0rem;
  float: right;
}
.avatar-content {
  display: block;
  font-weight: bolder;
  color: #FFFFFF;
  position: relative;
  top: 30%;
}
.el-aside{
  background-color: #FFFFFF;

}

.el-aside>>>.el-scrollbar__view{
  color: #6E7072;
}
.el-aside>>>.el-icon{
  color: #6E7072;
}
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
}
.el-main{
  overflow-y: hidden;
}
#logoBox{
  display: inline-block;
  float: left;
}
.el-sub-menu__title>span{
  color: #6E7072
}
.el-main{
  background-color:#F6F7F7;
}
.card-header{
  text-align: left;
}
.notification-wrapper {
  position: relative;
}

.notification-dot {
  position: absolute;
  top: -0.5vh;
  right: -0vw;
  width: 1.2rem;
  height: 1.2rem;
  background-color: red;
  border-radius: 50%;
  color: white;
  font-size: 0.6em;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
